package com.hk.springsecurity04.config;

import com.hk.springsecurity04.filter.CustomAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;

/**
 * @author by 何坤
 * @Classname WebSecurityConfig
 * @Description TODO
 * @Date 2019/12/23 16:25
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors()
                .and()
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/app/**", "/", "/login").permitAll()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                /*.successHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    httpServletResponse.setContentType("Application/json;charset=utf-8");
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.write("{\"success\":true, \"message\":\"登录成功\"}");
                    writer.flush();
                    writer.close();
                })
                .failureHandler((httpServletRequest, httpServletResponse, e) -> {
                    httpServletResponse.setContentType("Application/json;charset=utf-8");
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.write("{\"success\":true, \"message\":\"登录失败\"}");
                    writer.flush();
                    writer.close();
                })*/
                .and()
            .csrf().disable();
        http.addFilterAt(new CustomAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        filter.setAuthenticationSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
            httpServletResponse.setContentType("Application/json;charset=utf-8");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write("{\"success\":true, \"message\":\"登录成功\"}");
            writer.flush();
            writer.close();
        });
        filter.setAuthenticationFailureHandler((httpServletRequest, httpServletResponse, e) -> {
            httpServletResponse.setContentType("Application/json;charset=utf-8");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write("{\"success\":true, \"message\":\"登录失败\"}");
            writer.flush();
            writer.close();
        });
        filter.setFilterProcessesUrl("/login/self");
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }
}
